﻿using Furion.EventBus;
using Furion.FriendlyException;
using GMS.NET.Application.EventBus;
using GMS.NET.Const;
using GMS.NET.Core.Entitys.System;
using GMS.NET.Core.Options;
using GMS.NET.Core.Users;
using GMS.NET.Dto.System.Custs.Shared;
using GMS.NET.SqlSugarCore.DbCore;
using Mapster;

namespace GMS.NET.Application.Service.System.Custs
{
    [Authorize]
    [DynamicApiController]
    public class CustsService : DbManger, ICustsService
    {
        private readonly IEventPublisher events = App.GetService<IEventPublisher>();
        public async Task<bool> CheckUsersConfirmOperCustsNotes([FromBody] bool IsCheck)
        {
            if (IsCheck)
            {
                await MasterDb.Updateable<GMSNet_User>()
                    .SetColumns(x => x.User_OperCustsNotes == 1)
                    .Where(x => x.User_Account == UserInfo.UserId)
                    .ExecuteCommandAsync();
                return true;
            }
            else
            {
                var IsNotes = await MasterDb.Queryable<GMSNet_User>()
                    .Where(x => x.User_Account == UserInfo.UserId)
                    .Select(x => x.User_OperCustsNotes)
                    .FirstAsync(); 
                return IsNotes == 1;
            }
        }
        public async Task CustsStatus(int status, Guid Id)
        {
            var custsAdminId = App.GetOptions<UserAdminOptions>().CustsId;
            if (Id ==  Guid.Parse(UserInfo.CusId))
                throw Oops.Bah("不可修改跟操作人同客户状态");
            if (Id == Guid.Parse(custsAdminId!))
                throw Oops.Bah("不可修改系统管理员客户状态");
            await MasterDb.Updateable<GMSNet_Customer>()
                .SetColumns(x => x.Cust_Status == status)
                .Where(x => x.Id == Id)
                .ExecuteCommandAsync();
        }
        public async Task DelCustsData([FromBody] List<Guid> Ids)
        {
            if (Ids.Any(x=>x==Guid.Parse(UserInfo.CusId)))
                throw Oops.Bah("不可删除跟操作人同客户信息");
            var userAdmin = App.GetOptions<UserAdminOptions>();
            if (Ids.Any(x => x == new Guid(userAdmin.CustsId!)))
                throw Oops.Bah("不可删除管理员客户");
            if (await MasterDb.Queryable<GMSNet_Customer>().AnyAsync(x => x.Cust_Status == 2
            && Ids.Contains(x.Id)))
                throw Oops.Bah("不可再次删除已删除的客户");
            await MasterDb.Updateable<GMSNet_Customer>()
                .Where(x => Ids.Contains(x.Id))
                .SetColumns(x => x.Cust_Status == 2)
                .SetColumns(x => x.Cust_Deltime == DateTime.Now)
                .ExecuteCommandAsync();
        }
        [HttpPost]
        public async Task<TabularData<CustsData>> GetCustsData([FromBody] QueryPivot queryPivot)
        {
            RefAsync<int> total = 0;
            var result = await MasterDb.Queryable<GMSNet_Customer>()
                .WhereIF(!UserInfo.UserAdmin,x=>x.Id==Guid.Parse(UserInfo.CusId))
                .Where(queryPivot.WhereModel!.GetSearches())
                .OrderBy(x => x.Cust_Deltime)
                .Select<CustsData>()
                .ToPageListAsync(queryPivot.PageIndex, queryPivot.PageSize, total);
            return new TabularData<CustsData>() { Items = result, page_Total = total };
        }
        public async Task RecoverCustsData([FromBody] List<Guid> Ids)
        {
            if (Ids.Any())
                if (await MasterDb.Queryable<GMSNet_Customer>().AnyAsync(x => x.Cust_Status == 2 && Ids.Contains(x.Id)))
                    await MasterDb.Updateable<GMSNet_Customer>()
                         .Where(x => Ids.Contains(x.Id))
                         .SetColumns(x => x.Cust_Status == 1)
                         .SetColumns(x => x.Cust_Deltime == null)
                         .ExecuteCommandAsync();
                else
                    throw Oops.Bah("无可恢复客户信息");
            else
                throw Oops.Bah("无可恢复客户信息");
        }
        public async Task SaveCustsData([FromBody] CustsData custsData)
        {
            var Custs = custsData.Adapt<GMSNet_Customer>();
            if (Custs.Id != Guid.Empty)
            {
                var orgCusts = await MasterDb.Queryable<GMSNet_Customer>().InSingleAsync(Custs.Id);
                Custs.Cust_Seq = orgCusts.Cust_Seq;
                Custs.Creationtime = orgCusts.Creationtime;
                Custs.Creator = orgCusts.Creator;
                Custs.Cust_Connection = orgCusts.Cust_Connection;
                await MasterDb.Updateable(Custs)
                    .CallEntityMethod(it => it.SetUpdateUser())
                    .ExecuteCommandAsync();
            }
            else
            {
                Custs.Id = Guid.NewGuid();
                var CustsDbData = await MasterDb.Insertable(Custs)
                    .CallEntityMethod(it => it.SetAddUser())
                     .ExecuteReturnEntityAsync();
                var options = App.GetOptions<CustConnectionOptions>();
                var UnionCodeId = $"GMSNet{CustsDbData.Cust_Seq.ToString().PadLeft(3, '0')}";
                CustsDbData.Cust_Connection = $"Server={options.Server};Database={UnionCodeId};User Id={options.User_Id};Password={options.Password};TrustServerCertificate=true;";
                await MasterDb.Updateable(CustsDbData).ExecuteCommandAsync();
                // 初始化业务表
                if (CustsDbData.Cust_Status != 0 && CustsDbData.Cust_Status != 2)
                    await events.PublishAsync(EventBusConst.CustsAddInitializeDataBase,
                        new CustsAddEventParam() { Connection = CustsDbData.Cust_Connection, Id = UnionCodeId });
            }
        }
    }
}
